/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: PerpetualContractTradeFragment.java
 *   @Date: 19-6-17 下午3:52
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.ui;

import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bhex.depth.DepthData;
import com.bhex.depth.DepthView;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.view.WheelView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.enums.PRICE_TYPE;
import io.bhex.app.kline.bean.PriceDigits;
import io.bhex.app.main.ui.MainActivity;
import io.bhex.app.market.ui.OptionCoinDialogFragment;
import io.bhex.app.skin.view.SkinTabLayout;
import io.bhex.app.trade.adapter.BookListAdapter;
import io.bhex.app.trade.adapter.ContractOrderTypeFragmentPagerAdapter;
import io.bhex.app.trade.adapter.FuturesEntrustOrderAdapter;
import io.bhex.app.trade.adapter.FuturesPositionAdapter;
import io.bhex.app.trade.bean.BookListBean;
import io.bhex.app.trade.listener.BookClickListener;
import io.bhex.app.trade.presenter.PerpetualContractTradeFragmentPresenter;
import io.bhex.app.trade.utils.TradeUtil;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CoinUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.BookView;
import io.bhex.app.view.ClickProxy;
import io.bhex.app.view.InnerRecyclerView;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.app.view.StepView;
import io.bhex.app.view.TopBar;
import io.bhex.app.view.anim.AnimUtils;
import io.bhex.app.view.bean.Book;
import io.bhex.app.view.flocyTab.TabEntity;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.DevicesUtil;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.SP;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.Urls;
import io.bhex.sdk.account.EventLogin;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.AssetUtilsManager;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.enums.ORDER_ENTRUST_TYPE;
import io.bhex.sdk.enums.ORDER_SIDE;
import io.bhex.sdk.enums.ORDER_TYPE;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FuturensBaseToken;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.trade.bean.FuturesFundingRate;
import io.bhex.sdk.trade.bean.FuturesFundingRatesResponse;
import io.bhex.sdk.trade.futures.bean.FuturesOrderResponse;
import io.bhex.sdk.trade.futures.bean.FuturesPositionOrder;
import io.bhex.sdk.trade.futures.bean.TradableBean;

/**
 * ================================================
 * 描   述：永续合约交易
 * ================================================
 */
public class PerpetualContractTradeFragment extends BaseFragment<PerpetualContractTradeFragmentPresenter, PerpetualContractTradeFragmentPresenter.PerpetualContractTradeFragmentUI> implements PerpetualContractTradeFragmentPresenter.PerpetualContractTradeFragmentUI, AssetUtilsManager.IndexChangeInterface, View.OnClickListener, StepView.StepViewProgressListener, OnRefreshListener {

    private static final String TAG = "PerpetualContractTradeFragment";
    //book默认条数
    private static final int BOOK_LIST_DEFAULT_NUM = 10;
    //book默认显示条数
    private static final int BOOK_LIST_DEFAULT_VISIBLE_NUM = 6;
    /**
     * 订单委托方式
     */
    protected static final int PLACE_ORDER_MODE_ORDINARY = 0;   //普通委托
    protected static final int PLACE_ORDER_MODE_PLANNING = 1;   //计划委托

    //拖动条
    private StepView stepView;
    //买卖
    List<Book> bidBooks = new ArrayList<>();
    List<Book> askBooks = new ArrayList<>();
    private RelativeLayout tabBuySell;  //买入卖出TAB
    protected View headerView;
    protected RecyclerView recyclerView;
    protected String baseToken = "";
    protected String quoteToken = "";
    protected String baseTokenAsset = "";
    protected String quoteTokenAsset = "";
    protected String symbol = "";
    protected String exchangeId = "";
    private String mergeDigitsStr = "";
    private boolean bSetFirstPrice = false;
    /**
     * 顶部买卖tab
     ****/
    //默认为买
    protected boolean isBuyMode = true;
    protected TextView buyTabTx;
    protected TextView sellTabTx;
    //默认是限价
    protected boolean isLimitedPrice = true;
    //市场价
    protected TextView priceMarketTx;
    //盘口深度合并位数
    List<PriceDigits.DigitsItem> digitsList = new ArrayList<>();

    protected Button btnCreateOrder;
    protected CoinPairBean coinPairBean;
    protected TopBar topBar;
    //数量精度
    private String basePrecision;
    //价格精度
    private String quotePrecision;
    //每次价格变动，最小的变动单位
    private String minPricePrecision;
    //保证金精度
    private String marginPrecision;
    //最小交易数量
    private String minTradeQuantity;
    //最小交易额
    private String minTradeAmount;
    //价格保留位数
    protected int digitPrice;
    //数量保留位数
    protected int digitBase;
    //保证金精度
    private int digitMargin;
    //数量输入框
    protected EditText editAmount;
    protected TextView bookTitleAmount;
    protected TextView bookTitlePrice;
    protected TextView balanceAvailableTx;
    protected String stepViewMaxValue;
    protected TextView priceAbout;
    private String digitDepth = AppData.Config.DIGIT_DEPTH_DEFAULT;
    protected String baseTokenName = "";
    protected String quoteTokenName = "";
    private InnerRecyclerView bookListRv;
    private List<BookListBean> bookListData = new ArrayList<>();
    private BookListAdapter bookListAdapter;
    //默认首次加载币对
    protected boolean isFirst = true;
    private OptionsPickerView pvOptions;
    private List<String> bookShowModeList;
    private List<String> digitsNameList;
    protected RelativeLayout editPriceRela;
    protected RelativeLayout editAmountRela;
    protected EditText editPrice;
    protected TextView editPriceUnit;
    protected TextView editAmountUnit;

    protected View buySellTabBg;
    private PointLengthFilter pricePointFilter;
    private PointLengthFilter amountPointFilter;
    protected int digitAmount;
    protected TickerBean currentTicker;
    protected SmartRefreshLayout refreshLayout;
    private int mSelectOptionOfBookShowMode;
    private int mSelectOptionOfPricePrecision;
    protected SkinTabLayout orderTab;

    private HomeTradeControl mHomeControl;
    protected TextView balanceAvailableAboutTx;
    protected View triggerPriceRela;
    protected View placeOrderModeRela;
    protected TextView placeOrderMode;
    protected View placeOrderModeArrow;
    protected EditText triggerPrice;
    protected TextView triggerPriceUnit;
    //默认是限价模式
    protected String currentPriceType = PRICE_TYPE.INPUT.getPriceType();
    //默认委托单模式
    protected String currentEntrustOrderType = ORDER_ENTRUST_TYPE.LIMIT.getEntrustType();
    protected TextView lerverNumTv;
    protected View settings;
    protected FuturensBaseToken baseTokenFutures;
    private boolean isReverse;
    /**
     * xxxxxxxxx
     *****/
    private View mFuturesTitlelayout;
    private Timer timer;
    private TimerTask task;
    private static final int nPeriod = 1 * 1000;
    private static final int TIMER_MESSAGE = 0X1;
    private ArrayList<Pair<String, Fragment>> items;
    private FuturesPositionAdapter mPositionAdapter;


    private FuturesEntrustOrderAdapter openOrdersAdapter;
    private FuturesEntrustOrderAdapter planningEntrustAdapter;

    private List<FuturesOrderResponse> currentOrderDatas = new ArrayList<>();
    private List<FuturesPositionOrder> holdOrders = new ArrayList<>();
    private List<FuturesOrderResponse> mPlanningOrders = new ArrayList<>();
    private CommonTabLayout openCloseTab;
    private TextView futuresUnderlyingIndex;
    private TextView futuresUnderlyingIndexTitle;
    private TextView delivery_time;
    private View canCloseQuantityLL;    //可开平仓数
    private TextView closeNumTv;
    private View payMarginLL;
    private TextView payMarginTitle;
    private TextView payMargin;
    private FuturensBaseToken currentFutures;
    //默认是开仓状态
    private boolean isOpenStatus = true;
    private String currentSide = ORDER_SIDE.BUY_OPEN.getOrderSide();
    private TextView payMarginAbout;
    private View leverRela; //杠杆布局
    private Map<String, FuturesFundingRate> fundingRateMap = new HashMap<String, FuturesFundingRate>();   //资金费率
    private TextView deliveryTimeTile;
    private TextView fundingRateTitle;
    private TextView fundingRateTv;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    //标的指数更新
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIMER_MESSAGE:
                    try {
                        if (coinPairBean != null && baseTokenFutures != null) {
                            //TODO 指数token可能有问题 待定
                            String indexData = NumberUtils.roundFormatDown(AssetUtilsManager.GetInstance().getSymbolIndexOfFutures(baseTokenFutures.getDisplayIndexToken()), SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken));
                            futuresUnderlyingIndex.setText(indexData);
                        } else {
                            futuresUnderlyingIndex.setText("--");
                        }
                        FuturesFundingRate futuresFundingRate = fundingRateMap.get(coinPairBean.getSymbolId());
                        String actualFundingRate = futuresFundingRate.getFundingRate();
                        String fundingRate = NumberUtils.roundFormat(NumberUtils.mul("100", actualFundingRate), AppData.DIGIT_FUNDING_FEE_RATE) + "%";
                        fundingRateTv.setText(fundingRate);
                        if (NumberUtils.sub(actualFundingRate, "0") >= 0) {
                            fundingRateTv.setTextColor(getResources().getColor(R.color.green));
                        } else {
                            fundingRateTv.setTextColor(getResources().getColor(R.color.red));
                        }
                        if (futuresFundingRate != null) {
//                            futuresFundingRate.getCurServerTime()
                            long time = Long.valueOf(futuresFundingRate.getNextSettleTime()) - System.currentTimeMillis();
                            if (time <= 0) {
                                delivery_time.setText(getString(R.string.string_placeholder));
                                getPresenter().getSettleStatus();
                            } else {
                                int day = Math.round(time / 1000 / 60 / 60 / 24);
                                // 时
                                int hour = Math.round(time / 1000 / 60 / 60 % 24);
                                // 分
                                int minute = Math.round(time / 1000 / 60 % 60);
                                // 秒
                                int second = Math.round(time / 1000 % 60);

                                if (day > 0) {
                                    delivery_time.setText(day + getString(R.string.string_option_d));
                                } else {
                                    delivery_time.setText(hour + ":" + minute + ":" + second);
                                }
                            }
                        }
                    } catch (Exception e) {

                    }
                    break;
            }
        }
    };

    //默认显示当前委托tab
    private int currentShowOrdersTab = ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType();
    private ContractOrderTypeFragmentPagerAdapter orderTabAdapter;
    private ViewPager orderTabViewPager;
    private TradableBean mCurrentTradableInfo;
    private View balanceAvailableRela;
    private String displayTokenId = "";
    private String displayIndexToken = "";
    private String quantityUnit = "";
    private int currentOpenCloseTabPosition = 0;
    private boolean isHasContractHelp;
    private boolean isShowCumulativeVolume = true;

    /**
     * 设置默认币对
     *
     * @param coinpair
     */
    public void setDefalutCoinPair(CoinPairBean coinpair) {
        coinPairBean = coinpair;
    }

    public void setHomeControl(HomeTradeControl control) {
        mHomeControl = control;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_perpetual_trade_layout, null, false);
    }

    @Override
    protected void initViews() {
        super.initViews();
        pricePointFilter = new PointLengthFilter();
        amountPointFilter = new PointLengthFilter();
        quantityUnit = getString(R.string.string_futures_unit);
        //盘口布局显示模式 默认、买单、卖单
        bookShowModeList = TradeUtil.getShowModeList(getActivity());

        settings = viewFinder.find(R.id.settings);

        //标题栏
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightTextMargin(0, PixelUtils.dp2px(0));
        topBar.setTitleRightDrawable(R.mipmap.icon_drawer);
        topBar.setRightImg(R.mipmap.icon_kline);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(exchangeId) && !TextUtils.isEmpty(symbol)) {
                    IntentUtils.goKline(getActivity(), coinPairBean);
                }
            }
        });

        refreshLayout = viewFinder.find(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(this);
        //头部
        headerView = viewFinder.find(R.id.futures_header_trade_layout);

        isShowCumulativeVolume = MMKVManager.getInstance().loadBookQuantityShowMode();

        stepView = headerView.findViewById(R.id.stepView);
        tabBuySell = headerView.findViewById(R.id.tab);
        buySellTabBg = headerView.findViewById(R.id.tab_bg);
        buyTabTx = headerView.findViewById(R.id.tab_bid);
        sellTabTx = headerView.findViewById(R.id.tab_ask);

        //下单模式
        placeOrderModeRela = headerView.findViewById(R.id.placeOrderModeRela);
        placeOrderMode = headerView.findViewById(R.id.placeOrderMode);
        placeOrderModeArrow = headerView.findViewById(R.id.placeOrderModeArrow);

        //杠杆
        lerverNumTv = headerView.findViewById(R.id.lerverNum);

        //下单按钮
        btnCreateOrder = headerView.findViewById(R.id.btn_create_order);
        //价格估值
        priceAbout = headerView.findViewById(R.id.priceAbout);
        //市价显示View
        priceMarketTx = headerView.findViewById(R.id.priceMarket);

        //触发价
        triggerPriceRela = headerView.findViewById(R.id.trigger_price_rela);
        triggerPrice = headerView.findViewById(R.id.trigger_price);
        //下单价输入
        editPriceRela = headerView.findViewById(R.id.edit_price_rela);
        editPrice = headerView.findViewById(R.id.edit_price);
        //下单 数量 或 金额
        editAmountRela = headerView.findViewById(R.id.edit_amount_rela);
        editAmount = headerView.findViewById(R.id.edit_amount);

        //设置价格 数量精度过滤器
        triggerPrice.setFilters(new InputFilter[]{pricePointFilter});
        editPrice.setFilters(new InputFilter[]{pricePointFilter});
        editAmount.setFilters(new InputFilter[]{amountPointFilter});

        //价格 数量的单位
        triggerPriceUnit = headerView.findViewById(R.id.trigger_price_unit);
        editPriceUnit = headerView.findViewById(R.id.edit_price_unit);
        editAmountUnit = headerView.findViewById(R.id.edit_amount_unit);

        //数量输入监听
        editAmount.addTextChangedListener(new AmountTextWatcher());

        //盘口-数量标题
        bookTitleAmount = headerView.findViewById(R.id.title_amount);
        //盘口-价格标题
        bookTitlePrice = headerView.findViewById(R.id.title_price);

        ShadowDrawable.setShadow(triggerPriceRela);
        ShadowDrawable.setShadow(priceMarketTx);
        ShadowDrawable.setShadow(editPriceRela);
        ShadowDrawable.setShadow(editAmountRela);

        //订单tab
        orderTab = headerView.findViewById(R.id.tabLayout);

        //委托
        recyclerView = viewFinder.find(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView view, int scrollState) {

            }

            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                /*if(mHomeControl != null) {
                    final int offset = recyclerView.computeVerticalScrollOffset();
                    final int range = recyclerView.computeVerticalScrollRange() - recyclerView.computeVerticalScrollExtent();

                    if (offset > PixelUtils.dp2px(50)) {
                        mHomeControl.OnShowTab(false);
                    }else if( offset ==0 ){
                        mHomeControl.OnShowTab(true);
                    }
                }*/
            }
        });

        /**********/
        if (headerView != null)
            mFuturesTitlelayout = viewFinder.find(R.id.futures_trade_title);
        if (mFuturesTitlelayout != null)
            mFuturesTitlelayout.setVisibility(View.VISIBLE);

        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRiskSettingsList();
            }
        });

        topBar.setTitleOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//              KeyBoardUtil.closeKeybord(editAmount,getActivity());
                FragmentManager childFragmentManager = getFragmentManager();
                OptionCoinDialogFragment dialogFragment = new OptionCoinDialogFragment(ContractTradeFragment.TAB_FUTURES, coinPairBean, new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        AnimalUtils.rotateyAnimRun(topBar.getTitleIcon(), 180.0f, 0.0f);
                        getPresenter().getTicker();
                    }
                });
                dialogFragment.show(childFragmentManager, "dialog");
                QuoteApi.UnSubTickers();
                AnimalUtils.rotateyAnimRun(topBar.getTitleIcon(), 0.0f, 180.0f);

            }
        });

        //结算时间
        deliveryTimeTile = viewFinder.textView(R.id.reference_title1);
        delivery_time = viewFinder.textView(R.id.reference_value1);
        //资金费率
        fundingRateTitle = viewFinder.textView(R.id.reference_title1);
        fundingRateTv = viewFinder.textView(R.id.reference_value2);
        //标的指数
        futuresUnderlyingIndexTitle = viewFinder.textView(R.id.reference_title3);
        futuresUnderlyingIndex = viewFinder.textView(R.id.reference_value3);

        /******* 开平仓tab *****/
        openCloseTab = viewFinder.find(R.id.createTab);

        mTabEntities.add(new TabEntity(this.getResources().getString(R.string.string_contract_open), 0, 0));
        mTabEntities.add(new TabEntity(this.getResources().getString(R.string.string_contract_close), 0, 0));
        mTabEntities.add(new TabEntity(this.getResources().getString(R.string.string_contract_positions), 0, 0));
        openCloseTab.setTabData(mTabEntities);

        //杠杆布局
        leverRela = headerView.findViewById(R.id.leverRela);
        //可用余额+估值
        balanceAvailableRela = headerView.findViewById(R.id.avaliable_rela);
        balanceAvailableTx = headerView.findViewById(R.id.balance_available);
        balanceAvailableAboutTx = headerView.findViewById(R.id.balance_available_about);

        //可平仓数
        canCloseQuantityLL = headerView.findViewById(R.id.can_close_ll);
        closeNumTv = headerView.findViewById(R.id.can_close_quantity);

        payMarginLL = headerView.findViewById(R.id.margin_ll);
        payMarginTitle = headerView.findViewById(R.id.margin_title);
        //应付保证金
        payMargin = headerView.findViewById(R.id.margin);
        //应付保证金估值
        payMarginAbout = headerView.findViewById(R.id.margin_about);
        initOrderTabs();

        openOrdersAdapter = new FuturesEntrustOrderAdapter(getActivity(), currentOrderDatas);
        openOrdersAdapter.isFirstOnly(false);
        //openOrdersAdapter.addHeaderView(headerView);


        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        View emptyView = layoutInflater.inflate(R.layout.empty_layout, refreshLayout, false);
        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
        layoutParams.height = PixelUtils.dp2px(200);
//        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        emptyView.setLayoutParams(layoutParams);
        openOrdersAdapter.setHeaderFooterEmpty(true, true);
        openOrdersAdapter.setEmptyView(emptyView);
        openOrdersAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.revoke_order) {
                    FuturesOrderResponse itemModel = (FuturesOrderResponse) adapter.getData().get(position);
                    getPresenter().cancelOrder(itemModel);
                }
            }
        });
        recyclerView.setAdapter(openOrdersAdapter);


        mPositionAdapter = new FuturesPositionAdapter(getActivity(), holdOrders, new MarginAdjustDialog.OnDialogObserver() {
            @Override
            public void onShow(DialogInterface dialog) {
            }

            @Override
            public void onDismiss(DialogInterface dialog) {
            }

            @Override
            public void onReqHttpSuccess() {
            }

            @Override
            public void onReqHttpFaile() {
            }
        });
        mPositionAdapter.isFirstOnly(false);
        //historyEntrustAdapter.addHeaderView(headerView);
        View emptyView2 = layoutInflater.inflate(R.layout.empty_layout, refreshLayout, false);
        ViewGroup.LayoutParams layoutParams2 = emptyView2.getLayoutParams();
        layoutParams2.height = PixelUtils.dp2px(200);
        emptyView2.setLayoutParams(layoutParams2);
        mPositionAdapter.setHeaderFooterEmpty(true, true);
        mPositionAdapter.setEmptyView(emptyView2);
        mPositionAdapter.setEnableLoadMore(true);

        planningEntrustAdapter = new FuturesEntrustOrderAdapter(getActivity(), mPlanningOrders);
        planningEntrustAdapter.isFirstOnly(false);
        //historyEntrustAdapter.addHeaderView(headerView);
        View emptyView3 = layoutInflater.inflate(R.layout.empty_layout, refreshLayout, false);
        ViewGroup.LayoutParams layoutParams3 = emptyView3.getLayoutParams();
        layoutParams3.height = PixelUtils.dp2px(200);
        emptyView3.setLayoutParams(layoutParams3);
        planningEntrustAdapter.setHeaderFooterEmpty(true, true);
        planningEntrustAdapter.setEmptyView(emptyView3);
        planningEntrustAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.revoke_order) {
                    FuturesOrderResponse itemModel = (FuturesOrderResponse) adapter.getData().get(position);
                    getPresenter().cancelOrder(itemModel);
                }
            }
        });
        recyclerView.setAdapter(openOrdersAdapter);

        /**********/

        Bundle bundle = getArguments();
        if (bundle != null) {
            CoinPairBean bean = (CoinPairBean) bundle.getSerializable(AppData.INTENT.SYMBOLS);
            if (bean != null) {
                coinPairBean = bean;
            }

        }
        if (coinPairBean != null) {

            loadDefaultConfig(coinPairBean);
            //切换默认买入Tab
            switchBuySellTab(isBuyMode);
            switchPriceMode(isLimitedPrice);

        }
        bookListRv = headerView.findViewById(R.id.bookList);
        LinearLayoutManager linearEmpty = new LinearLayoutManager(getActivity());
        linearEmpty.setOrientation(LinearLayoutManager.VERTICAL);
        bookListRv.setLayoutManager(linearEmpty);
        initBookListRvAdapter();

        if (isBuyMode == false) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
                }
            }, 50);
        }
    }

    @Override
    protected PerpetualContractTradeFragmentPresenter.PerpetualContractTradeFragmentUI getUI() {
        return this;
    }

    @Override
    protected PerpetualContractTradeFragmentPresenter createPresenter() {
        return new PerpetualContractTradeFragmentPresenter();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (coinPairBean == null) {
            CoinPairBean tradeCoin = CoinUtils.getContractTradeCoin();
            if (tradeCoin != null) {
                coinPairBean = tradeCoin;
            } else {
                coinPairBean = SymbolDataManager.GetInstance().getDefaultFuturesTradeCoinPair();
            }
        }

        EventBus.getDefault().register(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onMessageEvent(CoinPairBean coinPairBeanParam) {

        if (coinPairBeanParam == null || coinPairBeanParam.baseTokenFutures == null)
            return;
        if (TextUtils.isEmpty(coinPairBeanParam.baseTokenFutures.getTokenId())) {
            return;
        }
        coinPairBean = coinPairBeanParam;
        String oldSymbol = symbol;
        boolean needSwitchTradeTab = coinPairBeanParam.isNeedSwitchTradeTab();
//        ToastUtils.showShort("Message "+needSwitchTradeTab);
        if (!needSwitchTradeTab) {
            if (!isFirst) {
                return;
            }
        }
        isFirst = false;

        if (isBuyMode != coinPairBeanParam.isBuyMode()) {
            if (coinPairBeanParam.isBuyMode()) {
                AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);
            } else {
                AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
            }
        }
        loadDefaultConfig(coinPairBeanParam);
        if (!oldSymbol.equals(coinPairBeanParam.getSymbolId())) {
            /******* 切换了新的币对 需要重新拉取新的币对相关信息 *****/
            //默认设置到开仓状态
            isOpenStatus = true;
            setOpenCloseTab(0);
            //设置默认杠杆数
            setDefaultLeverNum();

            switchBuySellTab(isBuyMode);
//            updateUnit();
            getPresenter().resetAllData(coinPairBeanParam);

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onMessageEvent(EventLogin eventLogin) {
        switchBuySellTab(isBuyMode);
    }

    @Override
    public void onResume() {
        super.onResume();
        topBar.setTitleRightDrawable(R.mipmap.icon_drawer);
        ShadowDrawable.setShadow(triggerPriceRela);
        ShadowDrawable.setShadow(priceMarketTx);
        ShadowDrawable.setShadow(editPriceRela);
        ShadowDrawable.setShadow(editAmountRela);

        if (coinPairBean != null) {
            switchBuySellTab(isBuyMode);

            if (!UserInfo.isLogin()) {
                if (!UserInfo.isLogin()) {
                    if (currentOrderDatas.size() > 0) {
                        currentOrderDatas.clear();
                        if (openOrdersAdapter != null) {
                            openOrdersAdapter.setNewData(currentOrderDatas);
                        }
                    }
                    if (mPlanningOrders.size() > 0) {
                        mPlanningOrders.clear();
                        if (planningEntrustAdapter != null) {
                            planningEntrustAdapter.setNewData(mPlanningOrders);
                        }
                    }

                }

            }
        }

    }

    /**
     * 初始化booklist适配器
     */
    private void initBookListData() {
        bookListData.clear();
        askBooks.clear();
        bidBooks.clear();
        for (int i = 0; i < BOOK_LIST_DEFAULT_NUM; i++) {
            BookListBean bookListBean = new BookListBean(BookListBean.TYPE_BOOK);
            Book book1 = new Book();
            book1.setBid(false);
            book1.setPrice(getString(R.string.string_placeholder));
            book1.setVolume(getString(R.string.string_placeholder));
            book1.setPriceColor(getResources().getColor(R.color.red));
            book1.setProgressColor(getResources().getColor(R.color.red10));
            book1.setProgress(0f);
            book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
            bookListBean.setBook(book1);
            bookListData.add(bookListBean);
            askBooks.add(book1);

        }
        BookListBean bookListBean = new BookListBean(BookListBean.TYPE_LASTPRICE);
        bookListBean.setLastPrice(getString(R.string.string_placeholder));
        bookListBean.setLegalPrice(getString(R.string.string_placeholder));
        bookListData.add(bookListBean);

        for (int i = 0; i < BOOK_LIST_DEFAULT_NUM; i++) {
            BookListBean bookListBean2 = new BookListBean(BookListBean.TYPE_BOOK);
            Book book1 = new Book();
            book1.setBid(true);
            book1.setPrice(getString(R.string.string_placeholder));
            book1.setVolume(getString(R.string.string_placeholder));
            book1.setPriceColor(getResources().getColor(R.color.green));
            book1.setProgressColor(getResources().getColor(R.color.green10));
            book1.setProgress(0f);
            book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
            bookListBean2.setBook(book1);
            bookListData.add(bookListBean2);
            bidBooks.add(book1);

        }
    }

    private void initBookListRvAdapter() {

        initBookListData();

        bookListAdapter = new BookListAdapter(bookListData, new BookClickListener() {
            @Override
            public void onItemClick(View view, String price) {
                //点击挂单条目，赋值价格
                setPrice(price);
//                AnimalUtils.scaleAnimRun(editPrice,0.5f,1.0f);
                AnimUtils.onScaleAnimation(editPrice);

            }
        });
        bookListRv.setAdapter(bookListAdapter);
        bookListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.btn_setting) {
                    showBookSetting();
                }
            }
        });
/*        if (Build.VERSION.SDK_INT >= 23) {
            bookListRv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(scrollY * 2 == (BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM) *v.getHeight()){

                        bookListRv.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_CANCEL, 0, 0, 0));
                    }
                }
            });
        }
        bookListRv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_CANCEL:
                        //setSelection(Integer.MAX_VALUE / 2);
                        return true;
                    default:
                        break;
                }
                return false;
            }
        });*/

       /* LinearLayoutManager linearLayoutManager = new
                LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false);
        bookListRv.setLayoutManager(linearLayoutManager);

        CustomSnapHelper mMySnapHelper = new CustomSnapHelper();
        mMySnapHelper.attachToRecyclerView(bookListRv);*/

        bookListRv.setOnFlingListener(new RecyclerView.OnFlingListener() {
            @Override
            public boolean onFling(int velocityX, int velocityY) {
                int height = bookListRv.getMeasuredHeight();
                int first = bookListRv.getChildLayoutPosition(bookListRv.getChildAt(0));
                if (velocityY < 0 && first >= 5) {
                    bookListRv.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);
                        }
                    });
                } else if (velocityY > 0 && first <= 5) {
                    bookListRv.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);
                        }
                    });
                }
                return false;
            }
        });
        srollBookDefault();
    }

    /**
     * 盘口列表滑动至中间
     */
    private void srollBookDefault() {
        if (bookListRv != null && bookListAdapter != null) {
            bookListRv.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);
                }
            }, 100);
        }
    }

    @Override
    public boolean isSelected() {
        if (mHomeControl != null) {
            return mHomeControl.IsSelected();
        }

        Bundle arguments = getArguments();
        boolean isSelect = true;
        if (arguments != null) {
            isSelect = arguments.getBoolean("isSelect", true);
        }
        return isSelect;
    }

    /**
     * 盘口设置
     */
    private void showBookSetting() {
        KeyBoardUtil.closeKeybord(editAmount, getContext());
        pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                mSelectOptionOfBookShowMode = options1;
                mSelectOptionOfPricePrecision = option2;
                if (options1 == 0) {
                    //切换到:默认
                    scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);

                } else if (options1 == 1) {
                    //切换到:显示买单
                    scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM);

                } else if (options1 == 2) {
                    //切换到:显示卖单
                    scrollToPosition(bookListRv, 0);
                }

                if (!digitsList.isEmpty()) {

                    //深度小数通知
                    digitDepth = digitsList.get(option2).getDigits();
//                    String digitsName = digitsList.get(option2).getDigitsName();
//                    viewFinder.textView(R.id.digit).setText(digitsName);
                    getPresenter().changeMergeDigit(digitDepth);
                }
            }
        })
                .setSubmitText(getResources().getString(R.string.string_sure))//确定按钮文字
                .setCancelText(getResources().getString(R.string.string_cancel))//取消按钮文字
//                    .setTitleText("盘口设置")//标题
                .setSubCalSize(16)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark))//标题文字颜色
                .setSubmitColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.green_night : R.color.green))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.color_bg_2_night : R.color.color_bg_2))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.color_bg_2_night : R.color.color_bg_2))//滚轮背景颜色 Night mode
                .setDividerColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.divider_line_color_night : R.color.divider_line_color))
                .setDividerType(WheelView.DividerType.FILL)
                .setContentTextSize(14)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark))
                .setTextColorOut(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.grey2))
                .setLineSpacingMultiplier(2.5f)
                .setTypeface(Typeface.DEFAULT_BOLD)
//                .setTextXOffset(10,30,50)
//                            .setLinkage(false)//设置是否联动，默认true
//                    .setLabels("显示", "小数", "")//设置选择的三级单位
//                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .build();

        pvOptions.setNPicker(bookShowModeList, digitsNameList, null);//添加数据源
        pvOptions.setSelectOptions(mSelectOptionOfBookShowMode, mSelectOptionOfPricePrecision);
        pvOptions.show();
    }

    /**
     * 底部订单tab
     */
    private void initOrderTabs() {
        items = new ArrayList<>();
        items.add(new Pair<String, Fragment>(getString(R.string.string_ordinary_entrument), null));
        items.add(new Pair<String, Fragment>(getString(R.string.string_planning_entrument), null));

        orderTabAdapter = new ContractOrderTypeFragmentPagerAdapter(getChildFragmentManager(), items);
        orderTabViewPager = headerView.findViewById(R.id.clViewPager);
        orderTabViewPager.getCurrentItem();
        orderTabViewPager.setAdapter(orderTabAdapter);
        orderTab.setupWithViewPager(orderTabViewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white),getResources().getColor(R.color.color_black));
        orderTab.setTabMode(TabLayout.MODE_SCROLLABLE);
        orderTab.setTabGravity(TabLayout.GRAVITY_CENTER);
        orderTabViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    //普通委托
                    currentShowOrdersTab = ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType();
                    getPresenter().switchOrderList(ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType());
                } else if (position == 1) {
                    //计划委托
                    currentShowOrdersTab = ORDER_TYPE.ORDER_TYPE_PLANNING_ENTRUSTMENT.getOrderType();
                    getPresenter().switchOrderList(ORDER_TYPE.ORDER_TYPE_PLANNING_ENTRUSTMENT.getOrderType());
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        CommonUtil.setUpIndicatorWidthByReflex(orderTab, 15, 15);
    }

    @Override
    public void OnIndexChanged() {
        if (coinPairBean != null && baseTokenFutures != null) {
            String indexData = NumberUtils.roundFormatDown(AssetUtilsManager.GetInstance().getSymbolIndexOfFutures(baseTokenFutures.getIndexToken()), SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken));
            futuresUnderlyingIndex.setText(indexData);
        }
    }

    /**
     * 下单委托模式UI控制
     *
     * @param placeOrderMode
     */
    protected void placeOrderModeControl(int placeOrderMode) {
        if (placeOrderMode == PLACE_ORDER_MODE_ORDINARY) {
            //普通委托
            triggerPriceRela.setVisibility(View.GONE);

            priceModeControl(0, KlineUtils.getPriceTypeTxt(getActivity(), PRICE_TYPE.INPUT.getPriceType()));
            editPriceUnit.setTextAppearance(getActivity(), R.style.Body_Blue_Bold);
        } else if (placeOrderMode == PLACE_ORDER_MODE_PLANNING) {
            //计划委托
            triggerPriceRela.setVisibility(View.VISIBLE);
            priceModeControl(0, KlineUtils.getPriceTypeTxt(getActivity(), PRICE_TYPE.INPUT.getPriceType()));
            editPriceUnit.setTextAppearance(getActivity(), R.style.Body_Grey);
            if (!TextUtils.isEmpty(displayTokenId)) {
                editPriceUnit.setText(displayTokenId);
            }
        }
        setPriceHintUnit();
    }

    /**
     * 结算状态更新
     */
    private void startTimer() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(TIMER_MESSAGE);
            }
        };
        timer.schedule(task, 50, nPeriod);
    }

    private void stopTimer() {

        if (task != null) {
            task.cancel();
        }

        if (timer != null) {
            timer.purge();
            timer.cancel();
        }
    }

    /**
     * 更新单位
     */
    protected void updateUnit() {
        if (baseTokenFutures != null) {
            bookTitlePrice.setText(getString(R.string.string_price_ph, baseTokenFutures.getDisplayTokenId()));
//            bookTitleAmount.setText(getString(R.string.string_amount_format, quantityUnit));
            bookTitleAmount.setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, quantityUnit));

            triggerPriceUnit.setText(baseTokenFutures.getDisplayTokenId());
            editAmount.setHint(getResources().getString(R.string.string_amount));
            editAmountUnit.setText(quantityUnit);
            updateStepViewRange();
        }
    }

    /**
     * 更新步长进度条大小范围
     */
    protected void updateStepViewRange() {
        if (isOpenStatus) {//开仓
            stepViewMaxValue = calMaxOpenQuantity();
        } else {//平仓
            stepViewMaxValue = getCanCloseNum(isBuyMode);
        }
        updateStepViewValue(editAmount.getText().toString());
    }

    /**
     * 计算最大可开手数
     * 最大可开仓手数 =(可用保证金*杠杆)/(最新价格*合约乘数)
     */
    private String calMaxOpenQuantity() {
        if (baseTokenFutures != null) {
            String price = "";
            String inputPrice = getInputPrice();
            if (TextUtils.isEmpty(inputPrice)) {
                if (currentTicker != null) {
                    String lastPrice = currentTicker.getC();
                    if (!TextUtils.isEmpty(lastPrice)) {
                        price = getTransferPrice(lastPrice);
                    }
                }
            } else {
                price = inputPrice;
            }
            String quoteTokenAsset = getQuoteTokenAsset();
            String leverNum = getLeverNum();
            String contractMultiplier = baseTokenFutures.getContractMultiplier();
            if (TextUtils.isEmpty(price) || TextUtils.isEmpty(leverNum) || TextUtils.isEmpty(contractMultiplier)) {
                return "";
            } else {
                double a = NumberUtils.mul(quoteTokenAsset, leverNum);
                double b = NumberUtils.mul(price, contractMultiplier);
//            String maxOpenQuantity = NumberUtils.div(b,a)+"";

                String maxOpenQuantity = NumberUtils.roundFormatDown(NumberUtils.div(b, a), digitBase);
                return maxOpenQuantity;
            }
        } else {
            return "";
        }
    }

    protected String getQuoteTokenAsset() {
        return quoteTokenAsset;
    }

    protected String getCanCloseNum(boolean isBuyMode) {
        if (mCurrentTradableInfo != null) {
            return isBuyMode ? mCurrentTradableInfo.getShortAvailable() : mCurrentTradableInfo.getLongAvailable();
        } else {
            return "0";
        }
    }

    /**
     * 加载币对默认配置
     *
     * @param mCoinPairBean
     */
    protected void loadDefaultConfig(CoinPairBean mCoinPairBean) {
        if (mCoinPairBean != null && mCoinPairBean.baseTokenFutures != null && !TextUtils.isEmpty(mCoinPairBean.baseTokenFutures.getTokenId())) {
            coinPairBean = mCoinPairBean;
            baseTokenFutures = coinPairBean.baseTokenFutures;
            isReverse = coinPairBean.isReverse();
            isBuyMode = mCoinPairBean.isBuyMode();
            symbol = mCoinPairBean.getSymbolId();
            baseToken = mCoinPairBean.getBaseTokenId();
            baseTokenName = mCoinPairBean.getBaseTokenName();
            quoteToken = mCoinPairBean.getQuoteTokenId();
            quoteTokenName = mCoinPairBean.getQuoteTokenName();
            //价格单位
            displayTokenId = baseTokenFutures.getDisplayTokenId();
            displayIndexToken = baseTokenFutures.getDisplayIndexToken();

            if (!TextUtils.isEmpty(mCoinPairBean.getSymbolName())) {
                topBar.setTitle(mCoinPairBean.getBaseTokenName() + "/" + mCoinPairBean.getQuoteTokenName());
            }
            exchangeId = mCoinPairBean.getExchangeId();
            mergeDigitsStr = mCoinPairBean.getDigitMerge();
            handleMegeDigitData(mergeDigitsStr);
            basePrecision = mCoinPairBean.getBasePrecision();
            quotePrecision = mCoinPairBean.getQuotePrecision();
            minPricePrecision = mCoinPairBean.getMinPricePrecision();
            marginPrecision = baseTokenFutures.getMarginPrecision();
            digitDepth = minPricePrecision;
            minTradeQuantity = mCoinPairBean.getMinTradeQuantity();
            minTradeAmount = mCoinPairBean.getMinTradeAmount();
            digitBase = NumberUtils.calNumerCount(getActivity(), basePrecision);
            digitPrice = NumberUtils.calNumerCount(getActivity(), minPricePrecision);
            digitAmount = NumberUtils.calNumerCount(getActivity(), quotePrecision);
            digitMargin = NumberUtils.calNumerCount(getActivity(), marginPrecision);
            pricePointFilter.setDecimalLength(digitPrice);
            amountPointFilter.setDecimalLength(digitBase);

            //重置view数据状态

            editPrice.setText("");
            editAmount.setText("");
            stepView.setStepProgress(0f);
            srollBookDefault();
            setFirstPrice();
            mSelectOptionOfBookShowMode = 0;
            mSelectOptionOfPricePrecision = 0;
            //合并小数位数-初始化位数联动处理
            if (digitsList != null) {
                if (!digitsList.isEmpty()) {
                    for (PriceDigits.DigitsItem digitsItem : digitsList) {
                        String digits = digitsItem.getDigits();
                        if (!TextUtils.isEmpty(minPricePrecision) && !TextUtils.isEmpty(digits)) {
                            if (minPricePrecision.equals(digits)) {
                                mSelectOptionOfPricePrecision = digitsList.indexOf(digitsItem);
                                break;
                            }
                        }
                    }
                }
            }

        } else {
//            ToastUtils.showShort(getString(R.string.string_net_exception));
        }

        if (coinPairBean.baseTokenFutures != null && !TextUtils.isEmpty(coinPairBean.getSymbolName()) && !TextUtils.isEmpty(coinPairBean.baseTokenFutures.getTokenId())) {
            topBar.setLeftImgVisible(View.GONE);
            topBar.setTitle(coinPairBean.getSymbolName());
            DebugLog.d("ABBB====>", "name===" + coinPairBean.getSymbolName());
            topBar.setTitleAppearance(R.style.BodyL_Dark_Bold);
            //topBar.setTitleLength(180);

            currentFutures = coinPairBean.baseTokenFutures;
        }

        //设置数量的单位
        editAmountUnit.setText(quantityUnit);
        setPriceHintUnit();

        stopTimer();
        startTimer();

        //设置默认杠杆数
        setDefaultLeverNum();
        //默认设置到开仓状态
        isOpenStatus = true;
        setOpenCloseTab(0);

        getPresenter().getOrderSetting(coinPairBean);
        getPresenter().getSettleStatus();
        getPresenter().getTradableInfo(coinPairBean.getSymbolId());
        getPresenter().subTradableInfo(coinPairBean.getSymbolId());
    }

    /**
     * 设置价格输入框的 hint 提示单位
     */
    private void setPriceHintUnit() {
        if (currentEntrustOrderType.equals(ORDER_ENTRUST_TYPE.LIMIT.getEntrustType())) {
            editPrice.setHint(getString(R.string.string_price) + "(" + displayTokenId + ")");
        } else {
            editPrice.setHint(getString(R.string.string_price));
        }
    }

    private void setDefaultLeverNum() {
        if(baseTokenFutures==null){
            return;
        }
        List<String> leversOfAll = baseTokenFutures.getLevers();    //原始全部杠杆列表
        if (leversOfAll != null && leversOfAll.size() > 0) {
            int size = leversOfAll.size();
            int selectLeverPosition = size % 2 == 0 ? (size - 1) / 2 : size / 2;
            String lever = leversOfAll.get(selectLeverPosition);
//            setLeverNumText(lever + "X");
            // 默认的不保存，防止覆盖客户选择
            lerverNumTv.setText(lever + "X");
        }

//        for (int i = 0; i < leversOfAll.size(); i++) {
//            if(i==0){
//                String lever = leversOfAll.get(i);
//                setLeverNumText(lever + "X");
//                break;
//            }
//        }
    }

    private void setLeverNumText(String leverTxt) {
        lerverNumTv.setText(leverTxt);
        if (coinPairBean != null) {
            String key = coinPairBean.getSymbolId() + isBuyMode;
            SPEx.set(key, leverTxt);
        }
    }

    @Override
    public String getQuoteToken() {
        return quoteToken;
    }

    @Override
    public String getBaseToken() {
        return baseToken;
    }

    private void handleMegeDigitData(String mergeDigitsStr) {
        if (!TextUtils.isEmpty(mergeDigitsStr)) {
            String[] digitsArray = mergeDigitsStr.split(",");
            if (digitsArray.length > 0) {
                digitsList.clear();
                for (String s : digitsArray) {
                    PriceDigits.DigitsItem digitsItem = new PriceDigits.DigitsItem();
                    String name = NumberUtils.calNumerName(getActivity(), s);
                    digitsItem.setDigitsName(name);
                    digitsItem.setDigits(s);
                    digitsList.add(digitsItem);
                }
                String[] itemNames = new String[digitsList.size()];
                for (int i = 0; i < digitsList.size(); i++) {
                    itemNames[i] = digitsList.get(i).getDigitsName();
                }

                digitsNameList = Arrays.asList(itemNames);
            }

        }
    }

    /**
     * 设置第一次价格
     *
     * @param
     */
    private void setFirstPrice() {

        editPrice.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (currentTicker != null) {
                    String symbol = currentTicker.getS();
                    if (!TextUtils.isEmpty(symbol)) {
                        if (symbol.equals(getSymbols()) && bSetFirstPrice == false) {
                            setPrice(currentTicker.getC());
                            bSetFirstPrice = true;
                        }
                    }
                }
            }
        }, 500);
    }

    /**
     * 设置价格
     *
     * @param price
     */
    private void setPrice(String price) {
        if (TextUtils.isEmpty(price)) {
            price = "";
        }
        if (price.contains("-")) {
            price = "";
        }
        editPrice.setText(price);
        setPriceAbout(price);
    }

    /**
     * 设置价格估值
     *
     * @param price
     */
    private void setPriceAbout(String price) {
        if (TextUtils.isEmpty(price)) {
            price = "";
        }
        if (price.contains("-")) {
            price = "";
        }
        if (!TextUtils.isEmpty(price) && !TextUtils.isEmpty(displayTokenId)) {
            String legalMoney = RateDataManager.CurRatePrice(displayTokenId, price);
            legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
            priceAbout.setText("≈" + legalMoney);
        } else {
            priceAbout.setText(getString(R.string.string_placeholder));
        }
    }

    /**
     * 设置交易量/额
     *
     * @param value
     */
    private void setAmount(String value) {
        if (TextUtils.isEmpty(value)) {
            editAmount.setText("");
        } else {
            if (NumberUtils.sub(value, "0") <= 0) {
                editAmount.setText("");
            } else {
                editAmount.setText(value);
            }
        }
    }

    /**
     * 数量输入框监听器
     */
    class AmountTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateStepViewValue(s.toString());
            updateTradeAmountOfMoney();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    /**
     * 更新步长值
     *
     * @param quantity
     */
    protected void updateStepViewValue(String quantity) {
        if (TextUtils.isEmpty(quantity) || TextUtils.isEmpty(stepViewMaxValue)) {
            stepView.setStepProgress(0);
        } else {
            float progress = Float.valueOf(NumberUtils.div(stepViewMaxValue, quantity, 2) + "");
            stepView.setStepProgress(progress);
        }
    }

    /**
     * 设置选择-开平仓持仓tab
     *
     * @param position
     */
    private void setOpenCloseTab(int position) {
        openCloseTab.setCurrentTab(0);

        if (position == 0) {
            //开仓
            switchOpenClose(true);
//                    switchBuySellTab(isBuyMode,getString(R.string.string_option_purchase),getString(R.string.string_option_sellout));
            int currentOrderTabSelectItem = getCurrentOrderTabSelectItem();
            setCurrentShowOrderTab(currentOrderTabSelectItem);
            getPresenter().switchCurrentOrderList(currentOrderTabSelectItem);
            //头布局控制，持仓隐藏头部
            headerView.setVisibility(View.VISIBLE);
        } else if (position == 1) {
            //平仓
            switchOpenClose(false);
//                    switchBuySellTab(isBuyMode,getString(R.string.string_contract_close_short),getString(R.string.string_contract_close_long));
            int currentOrderTabSelectItem = getCurrentOrderTabSelectItem();
            setCurrentShowOrderTab(currentOrderTabSelectItem);
            getPresenter().switchCurrentOrderList(currentOrderTabSelectItem);
            //头布局控制，持仓隐藏头部
            headerView.setVisibility(View.VISIBLE);
        } else if (position == 2) {
            if (!UserInfo.isLogin()) {
                //去登录
                IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                openCloseTab.setCurrentTab(currentOpenCloseTabPosition);
                return;
            } else {
                currentShowOrdersTab = ORDER_TYPE.ORDER_TYPE_HOLD.getOrderType();
                getPresenter().switchOrderList(ORDER_TYPE.ORDER_TYPE_HOLD.getOrderType());
                //头布局控制，持仓隐藏头部
                headerView.setVisibility(View.GONE);
            }
        }
        currentOpenCloseTabPosition = position;
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        //开平仓tab
        openCloseTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) {
                    //开仓
                    switchOpenClose(true);
//                    switchBuySellTab(isBuyMode,getString(R.string.string_option_purchase),getString(R.string.string_option_sellout));
                    int currentOrderTabSelectItem = getCurrentOrderTabSelectItem();
                    setCurrentShowOrderTab(currentOrderTabSelectItem);
                    getPresenter().switchCurrentOrderList(currentOrderTabSelectItem);
                    //头布局控制，持仓隐藏头部
                    headerView.setVisibility(View.VISIBLE);
                } else if (position == 1) {
                    //平仓
                    switchOpenClose(false);
//                    switchBuySellTab(isBuyMode,getString(R.string.string_contract_close_short),getString(R.string.string_contract_close_long));
                    int currentOrderTabSelectItem = getCurrentOrderTabSelectItem();
                    setCurrentShowOrderTab(currentOrderTabSelectItem);
                    getPresenter().switchCurrentOrderList(currentOrderTabSelectItem);
                    //头布局控制，持仓隐藏头部
                    headerView.setVisibility(View.VISIBLE);
                } else if (position == 2) {
                    if (!UserInfo.isLogin()) {
                        //去登录
                        IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                        openCloseTab.setCurrentTab(currentOpenCloseTabPosition);
                        return;
                    } else {
                        currentShowOrdersTab = ORDER_TYPE.ORDER_TYPE_HOLD.getOrderType();
                        getPresenter().switchOrderList(ORDER_TYPE.ORDER_TYPE_HOLD.getOrderType());
                        //头布局控制，持仓隐藏头部
                        headerView.setVisibility(View.GONE);
                    }
                }
                currentOpenCloseTabPosition = position;

            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        headerView.findViewById(R.id.leverRela).setOnClickListener(this);
        headerView.findViewById(R.id.btnTransfer).setOnClickListener(this);
        stepView.setOnProgressListener(this);
        headerView.findViewById(R.id.tab_bid_rela).setOnClickListener(this);
        headerView.findViewById(R.id.tab_ask_rela).setOnClickListener(this);
        headerView.findViewById(R.id.placeOrderModeRela).setOnClickListener(this);
        headerView.findViewById(R.id.edit_amount).setOnClickListener(this);
        headerView.findViewById(R.id.look_all_order).setOnClickListener(this);

        //book列表滑动监听
        bookListRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    mShouldScroll = false;
                    smoothMoveToPosition(bookListRv, mToPosition);
                }
            }
        });

        editPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setPriceAbout(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                updateTradeAmountOfMoney();
                updateUnit();
                updateMaxCanOpenCloseQuantity();
            }
        });

        //下单
        btnCreateOrder.setOnClickListener(new ClickProxy(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DevicesUtil.vibrate(getActivity(), 100);

                if (!UserInfo.isLogin()) {
                    //去登录
                    IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                } else {
                    createOrder(isBuyMode);
                }
            }
        }));

        editPriceUnit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPriceModeSelect();
            }
        });

        bookTitleAmount.setOnClickListener(this);
    }

    /**
     * 设置当前需要显示的订单tab
     *
     * @param currentOrderTabSelectItem
     */
    private void setCurrentShowOrderTab(int currentOrderTabSelectItem) {
        currentShowOrdersTab = currentOrderTabSelectItem == 0 ? ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType() : ORDER_TYPE.ORDER_TYPE_PLANNING_ENTRUSTMENT.getOrderType();
    }

    private int getCurrentOrderTabSelectItem() {
        return orderTabViewPager.getCurrentItem() == 0 ? ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType() : ORDER_TYPE.ORDER_TYPE_PLANNING_ENTRUSTMENT.getOrderType();
    }

    /**
     * 切换买卖tab
     *
     * @param isBuyModeParam
     */
    protected void switchBuySellTab(boolean isBuyModeParam) {
        isBuyMode = isBuyModeParam;
        clearData();
        editAmount.setText("");
        if (isBuyMode) {
            buyTabTx.setTextColor(getResources().getColor(R.color.green));
            sellTabTx.setTextColor(SkinColorUtil.getDark(this.getContext()));
//            buyTabRela.setBackgroundResource(R.drawable.bg_corner_rect_green);
//            sellTabRela.setBackgroundResource(R.color.white);
            ShadowDrawable.setShadow(tabBuySell);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_green);
            //AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);
        } else {
            buyTabTx.setTextColor(SkinColorUtil.getDark(this.getContext()));
            sellTabTx.setTextColor(getResources().getColor(R.color.red));
//            sellTabRela.setBackgroundResource(R.drawable.bg_corner_rect_red);
//            buyTabRela.setBackgroundResource(R.color.white);
            ShadowDrawable.setShadow(tabBuySell);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_red);
            //AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
        }

        updateUnit();
        updateBuySellTabAssociatedView(isBuyMode);

        updateMaxCanOpenCloseQuantity();

        if (isOpenStatus) {
            updateLevers();
        }

    }

    /**
     * 切换买卖tab
     *
     * @param isBuyModeParam
     * @param btnBuyText     按钮买文案
     * @param btnSellText    按钮卖文案
     */
//    protected void switchBuySellTab(boolean isBuyModeParam, String btnBuyText, String btnSellText) {
//        isBuyMode = isBuyModeParam;
//        editAmount.setText("");
//        buyTabTx.setText(btnBuyText);
//        sellTabTx.setText(btnSellText);
//        if (isBuyMode) {
//            buyTabTx.setTextColor(getResources().getColor(R.color.green));
//            sellTabTx.setTextColor(getResources().getColor(R.color.dark));
////            buyTabRela.setBackgroundResource(R.drawable.bg_corner_rect_green);
////            sellTabRela.setBackgroundResource(R.color.white);
//            ShadowDrawable.setShadow(tabBuySell);
//            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_green);
//            //AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);
//        } else {
//            buyTabTx.setTextColor(getResources().getColor(R.color.dark));
//            sellTabTx.setTextColor(getResources().getColor(R.color.red));
////            sellTabRela.setBackgroundResource(R.drawable.bg_corner_rect_red);
////            buyTabRela.setBackgroundResource(R.color.white);
//            ShadowDrawable.setShadow(tabBuySell);
//            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_red);
//            //AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
//        }
//
//        updateUnit();
//        updateContractBuySellTabAssociatedView(isBuyMode, btnBuyText, btnSellText);
//        updateInputPointLength();
//    }

    /**
     * 更新价格数量输入框的小数位数长度限制
     */
    private void updateInputPointLength() {
        pricePointFilter.setDecimalLength(digitPrice);
        amountPointFilter.setDecimalLength(digitBase);
    }

    /**
     * 更新可用资产
     *
     * @param token
     * @param tokenName
     */
    protected void updateAsset(String token, String tokenName) {
        String assetAvaliableOfToken = "";
        int digit = AppData.Config.DIGIT_DEFAULT_VALUE;
        if (token != null && token.equalsIgnoreCase(quoteToken)) {
            assetAvaliableOfToken = getQuoteTokenAsset();
        } else {
            assetAvaliableOfToken = getCanCloseNum(isBuyMode);
        }

        String available = NumberUtils.roundFormatDown(assetAvaliableOfToken, AppData.Config.DIGIT_DEFAULT_VALUE);
        if (!TextUtils.isEmpty(available)) {
            if (available.contains(".") && available.length() > 12) {
                available = available.substring(0, 12);
            }
        } else {
            available = NumberUtils.roundFormatDown("0", AppData.Config.DIGIT_DEFAULT_VALUE);
        }

        String legalMoney = RateDataManager.CurRatePrice(token, assetAvaliableOfToken);
        legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
        if (UserInfo.isLogin() && !TextUtils.isEmpty(available)) {
            balanceAvailableTx.setText(getString(R.string.string_balance_available_format, NumberUtils.roundFormatDown(String.valueOf(available), digitMargin), tokenName));
            balanceAvailableAboutTx.setText("≈" + legalMoney);
        } else {
            balanceAvailableTx.setText(getString(R.string.string_placeholder));
            balanceAvailableAboutTx.setText(getString(R.string.string_placeholder));
        }
    }

    /**
     * 更新买卖tab改变相关的View状态 标识
     *
     * @param isBuyMode
     */
    protected void updateBuySellTabAssociatedView(boolean isBuyMode) {
        //更新下单按钮状态
        btnCreateOrder.setBackgroundResource(isBuyMode ? R.drawable.bg_corner_green : R.drawable.bg_corner_red);
        updateCreateButtonStatus();
    }

    /**
     * 更新买卖tab改变相关的View状态 标识
     *
     * @param isBuyMode
     */
//    protected void updateContractBuySellTabAssociatedView(boolean isBuyMode, String openTxt, String closeTxt) {
//        //更新下单按钮状态
//        btnCreateOrder.setBackgroundResource(isBuyMode ? R.drawable.bg_corner_green : R.drawable.bg_corner_red);
//        if (!UserInfo.isLogin()) {
//            btnCreateOrder.setText(getString(R.string.string_login));
//        } else {
//            if (isBuyMode) {
//                btnCreateOrder.setText(getString(R.string.string_purchase) + "(" + openTxt + ") " + baseTokenName);
//            } else {
//                btnCreateOrder.setText(getString(R.string.string_sellout) + "(" + closeTxt + ")" + baseTokenName);
//            }
//        }
//    }

    /**
     * 切换限价/非限价
     *
     * @param isLimitedPriceParams
     */
    protected void switchPriceMode(boolean isLimitedPriceParams) {
        isLimitedPrice = isLimitedPriceParams;
        editAmount.setText("");

        updatePriceModeAssociatedView(isLimitedPrice);
        updateUnit();
    }

    /**
     * 更新价格模式关联View
     *
     * @param isLimitedPrice
     */
    protected void updatePriceModeAssociatedView(boolean isLimitedPrice) {
        if (isLimitedPrice) {
            editPriceRela.setVisibility(View.VISIBLE);
            priceMarketTx.setVisibility(View.GONE);
        } else {
            editPriceRela.setVisibility(View.GONE);
            priceMarketTx.setVisibility(View.VISIBLE);
            payMargin.setText(getString(R.string.string_placeholder));
            payMarginAbout.setText(getString(R.string.string_placeholder));
        }
    }

    @Override
    public void updateBookList() {
        getActivity().runOnUiThread(() -> {
            bookListAdapter.notifyDataSetChanged();
        });
    }

    public void scrollToPosition(RecyclerView rv, int position) {
        if (position != -1) {
            smoothMoveToPosition(rv, position);
        } else {
            smoothMoveToPosition(rv, position + 1);
        }
    }

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    @Override
    public void updateAssettByToken(String token, String asset) {
        if (!UserInfo.isLogin()) {
            if (!balanceAvailableTx.getText().toString().equals(getString(R.string.string_placeholder))) {
                balanceAvailableTx.setText(getString(R.string.string_placeholder));
                balanceAvailableAboutTx.setText(getString(R.string.string_placeholder));
            }
            return;
        }
        //重新触发一次单位更新（里面包括可用资产、步长更新）
        if (token.equalsIgnoreCase(quoteToken)) {
            quoteTokenAsset = asset;
        } else if (token.equalsIgnoreCase(baseToken)) {
            baseTokenAsset = asset;
        }
        updateUnit();
        updateAsset(quoteToken, quoteTokenName);
    }

    @Override
    public void resetView() {
        priceAbout.setText(getString(R.string.string_placeholder));
        balanceAvailableTx.setText(getString(R.string.string_placeholder));
        balanceAvailableAboutTx.setText(getString(R.string.string_placeholder));
        payMargin.setText(getString(R.string.string_placeholder));
        payMarginAbout.setText(getString(R.string.string_placeholder));
        closeNumTv.setText(getString(R.string.string_placeholder));
        updateLatestPrice(new TickerBean());
        initBookListData();
        bookListAdapter.notifyDataSetChanged();
//        editPrice.setText("");
        baseTokenAsset = "";
        quoteTokenAsset = "";
        bSetFirstPrice = false;
    }

    @Override
    public String getDigitStr() {
        return digitDepth;
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    protected void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (visible) {
            isShowCumulativeVolume = MMKVManager.getInstance().loadBookQuantityShowMode();
            setBookTitleAmount();

            editAmount.setTextAppearance(this.getContext(), CommonUtil.isBlackMode() ? R.style.Body_Dark_Bold_night : R.style.Body_Dark_Bold);
            editAmount.setHintTextColor(SkinColorUtil.getDark50(this.getContext()));
            editPrice.setTextAppearance(this.getContext(), CommonUtil.isBlackMode() ? R.style.Body_Dark_Bold_night : R.style.Body_Dark_Bold);
            editPrice.setHintTextColor(SkinColorUtil.getDark50(this.getContext()));

            if (!UserInfo.isLogin()) {
                balanceAvailableTx.setText(getString(R.string.string_placeholder));
                balanceAvailableAboutTx.setText(getString(R.string.string_placeholder));
                payMargin.setText(getString(R.string.string_placeholder));
                payMarginAbout.setText(getString(R.string.string_placeholder));
                closeNumTv.setText(getString(R.string.string_placeholder));
                baseTokenAsset = "";
                quoteTokenAsset = "";
                currentOrderDatas.clear();
                if (openOrdersAdapter != null) {
                    openOrdersAdapter.notifyDataSetChanged();
                }
                mPlanningOrders.clear();
                if (planningEntrustAdapter != null) {
                    planningEntrustAdapter.setNewData(mPlanningOrders);
                }
                return;
            } else {
                UserInfoBean userInfo = UserInfo.getUserInfo();
                if (!userInfo.openFuture) {
                    getPresenter().getUserInfo();
                }
            }
            AssetUtilsManager.GetInstance().AddIndexObserver(this);
        } else {
            AssetUtilsManager.GetInstance().removeIndexObserver(this);
        }
    }

    @Override
    public void showCheckOpenFutures() {
//        boolean isShowOpenFutures = SP.get("isShowOpenFutures", false);
//        if (!isShowOpenFutures) {
        checkOpenFutureStatus();
//        }
    }

    /**
     * 检查是否开通永续合约
     */
    private boolean checkOpenFutureStatus() {
        boolean isOpenFutures = false;
        if (UserInfo.isLogin()) {
            UserInfoBean userInfo = UserInfo.getUserInfo();
            if (!userInfo.openFuture) {
                showGoOpenFutures();
            } else {
                isOpenFutures = true;
            }
        }
        return isOpenFutures;
    }

    /**
     * 提示去开通永续合约
     */
    private void showGoOpenFutures() {
        SP.set("isShowOpenFutures", true);
        DialogUtils.showDialog(getActivity(), getString(R.string.string_title_open_futures), getString(R.string.string_open_futures_content_tips), getString(R.string.string_start_answer_question), getString(R.string.string_cancel), false, new DialogUtils.OnButtonEventListener() {
            @Override
            public void onConfirm() {
                WebActivity.runActivity(getActivity(), getString(R.string.string_title_open_futures), Urls.H5_URL_OPEN_FUTURES_PROTOCOL);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * 更新最新价
     */
    protected void updateLatestPrice(TickerBean tickerBean) {
        currentTicker = tickerBean;
        if (bSetFirstPrice == false) {
            setFirstPrice();
        }
        String legalMoney = "";
        if (baseTokenFutures != null) {
            legalMoney = RateDataManager.CurRatePrice(baseTokenFutures.getDisplayTokenId(), tickerBean.getC() + "");
            legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
        }


        if (bookListData.size() >= BOOK_LIST_DEFAULT_NUM) {
            BookListBean bookListOfLastPrice = bookListData.get(BOOK_LIST_DEFAULT_NUM);
            bookListOfLastPrice.setLastPrice(NumberUtils.roundingString(tickerBean.getC(), digitPrice));
            bookListOfLastPrice.setLegalPrice(legalMoney);
            bookListOfLastPrice.setChange(String.valueOf(NumberUtils.sub(tickerBean.getC(), tickerBean.getO())));
//            bookListData.set(BOOK_LIST_DEFAULT_NUM,bookListOfLastPrice);
            bookListAdapter.notifyDataSetChanged();
            TextView rightTextView = topBar.getRightTextView();
            rightTextView.setVisibility(View.VISIBLE);
            rightTextView.setText(KlineUtils.calRiseFallRatio(tickerBean.getC(), tickerBean.getO()));
            rightTextView.setTextColor(KlineUtils.getMarketViewColor(getActivity(), tickerBean.getC(), tickerBean.getO()));
        }

    }


    @Override
    public void onStepViewProgress(float progress) {
        if (TextUtils.isEmpty(stepViewMaxValue)) {
            return;
        }
        double result = NumberUtils.mul(stepViewMaxValue, progress + "");
        String value = NumberUtils.roundFormatDown(String.valueOf(result), digitBase);
        setAmount(value);
        updateTradeAmountOfMoney();
    }

    /**
     * 更新交易需要金额
     */
    protected void updateTradeAmountOfMoney() {
        if (isOpenStatus && currentPriceType.equals(PRICE_TYPE.INPUT.getPriceType())) {
            //开仓状态
            String amount = editAmount.getText().toString();
            String price = getInputPrice();
            if (TextUtils.isEmpty(price) && currentTicker != null) {
                //TODO 如果是开仓状态 价格为空 其他下单计价方式，暂时统一按照最新价估算
                price = getTransferPrice(currentTicker.getC());
            }
            if (currentFutures != null) {
                String leverNum = getLeverNum();
                String marginRate = NumberUtils.divStr(leverNum, "1");
                //合约乘数
                String contractMultiplier = currentFutures.getContractMultiplier();
                String tradeAmount = NumberUtils.roundFormatUp(NumberUtils.mul(NumberUtils.mul(NumberUtils.mul(price, amount) + "", contractMultiplier) + "", marginRate) + "", digitMargin);
                payMargin.setText(tradeAmount + " " + quoteToken);
                String legalMoneyOfTrade = RateDataManager.CurRatePrice(quoteToken, tradeAmount);
                legalMoneyOfTrade = RateDataManager.getShowLegalMoney(legalMoneyOfTrade, AppData.DIGIT_LEGAL_MONEY);
                payMarginAbout.setText(legalMoneyOfTrade);
            }
        } else {
            //平仓状态 TODO

        }
    }

    /**
     * 获取当前杠杆数
     *
     * @return
     */
    private String getLeverNum() {
        return lerverNumTv.getText().toString().trim().replaceAll("X", "");
    }

    /**
     * 获取当前输入价格
     *
     * @return
     */
    private String getInputPrice() {
        String price = editPrice.getText().toString().trim();
        return getTransferPrice(price);
    }

    /**
     * 获取真实价格
     *
     * @return
     */
    private String getTransferPrice(String price) {
        if (isReverse) {
            price = NumberUtils.divStr(price, "1");
        }
        return price;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_amount:
                break;
            case R.id.tab_bid_rela:
                //交易面板-买入
                switchBuySellTab(true);
                AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);

                break;
            case R.id.tab_ask_rela:
                //交易面板-卖出
                switchBuySellTab(false);
                AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());

                break;
            case R.id.placeOrderModeRela:
                //下单模式选择 普通委托/计划委托
                showPlaceOrderModeSelect();
                break;
            case R.id.look_all_order:
                if (!UserInfo.isLogin()) {
                    //去登录
                    IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                } else {
                    //全部订单
                    lookAllOrders();
                }
                break;
            case R.id.leverRela:
                if (!UserInfo.isLogin()) {
                    //去登录
                    IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                } else {
                    showLeverList();
                }
                break;
            case R.id.btnTransfer:
                if (!UserInfo.isLogin()) {
                    //去登录
                    IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                } else {
                    if (!TextUtils.isEmpty(quoteToken)) {
                        IntentUtils.goAssetTransfer(getActivity(), quoteToken);
                    }
                }
                break;
            case R.id.title_amount:
                showSelectBookQuantityTypeAlert();
                break;
        }
    }

    private void showSelectBookQuantityTypeAlert() {
        String[] quantityTypeArray = new String[]{getString(R.string.string_cumulative_quantity_format, quantityUnit), getString(R.string.string_amount_format, quantityUnit)};
        AlertView alertView = new AlertView(null, null, getString(R.string.string_cancel), quantityTypeArray, null, getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isShowCumulativeVolume = true;
                    setBookTitleAmount();
                    getPresenter().changeBookQuantityShowMode(isShowCumulativeVolume);
                    MMKVManager.getInstance().saveBookQuantityShowMode(isShowCumulativeVolume);
                } else if (position == 1) {
                    isShowCumulativeVolume = false;
                    setBookTitleAmount();
                    getPresenter().changeBookQuantityShowMode(isShowCumulativeVolume);
                    MMKVManager.getInstance().saveBookQuantityShowMode(isShowCumulativeVolume);
                }
            }
        });
        alertView.show();
    }

    private void setBookTitleAmount() {
        bookTitleAmount.setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, quantityUnit));
    }

    @Override
    public boolean isShowCumulativeVolume() {
        return isShowCumulativeVolume;
    }

    /**
     * 查看全部订单
     */
    protected void lookAllOrders() {
        //全部订单
        IntentUtils.goAllFuturesOrders(getActivity());
    }

    /**
     * 下单模式选择 普通委托/计划委托
     */
    private void showPlaceOrderModeSelect() {
        closeKeyBoard(editAmount);
        ArrayList<String> placeOrderModeList = new ArrayList<>();
        placeOrderModeList.add(getString(R.string.string_ordinary_entrument));
        placeOrderModeList.add(getString(R.string.string_planning_entrument));
        AlertView.showSheet(getActivity(), placeOrderModeList, null, null, getString(R.string.string_cancel), new AlertView.DialogListener() {
            @Override
            public void onShow(final AlertView alert) {
                ((MainActivity) getActivity()).registerBackKeyListener(new MainActivity.KeyBackListener() {
                    @Override
                    public void onKeyBack() {
                        alert.dismiss();
                    }
                });
            }

            @Override
            public void onDissmiss(AlertView alert) {
                ((MainActivity) getActivity()).removeBackKeyListener();
            }

            @Override
            public void onItemClick(int position, String item) {
                if (position == -1) {
                    return;
                }
                entrustOderType(position);
                placeOrderMode.setText(item);
                placeOrderModeControl(position);

            }
        });
    }

    /**
     * 委托类型
     *
     * @param position
     */
    private void entrustOderType(int position) {
        if (position == 0) {
            currentEntrustOrderType = ORDER_ENTRUST_TYPE.LIMIT.getEntrustType();
        } else if (position == 1) {
            currentEntrustOrderType = ORDER_ENTRUST_TYPE.STOP.getEntrustType();
        }
    }

    /**
     * 显示风险限额设置的选择
     */
    protected void showRiskSettingsList() {
        closeKeyBoard(editAmount);
        if (coinPairBean != null) {
            List<String> riskSettingList = new ArrayList<String>();
            final String contractHelpUrl = SymbolDataManager.GetInstance().getContractHelpUrl();
            if (!TextUtils.isEmpty(contractHelpUrl)) {
                riskSettingList.add(getString(R.string.string_contract_help));
                isHasContractHelp = true;
            } else {
                isHasContractHelp = false;
            }
            riskSettingList.add(getString(R.string.string_contract_calculator));
            riskSettingList.add(getString(R.string.string_set_hold_long_risk_limit));
            riskSettingList.add(getString(R.string.string_set_hold_short_risk_limit));
            AlertView.showSheet(getActivity(), riskSettingList, null, null, getString(R.string.string_cancel), new AlertView.DialogListener() {
                @Override
                public void onShow(final AlertView alert) {
                    ((MainActivity) getActivity()).registerBackKeyListener(new MainActivity.KeyBackListener() {
                        @Override
                        public void onKeyBack() {
                            alert.dismiss();
                        }
                    });
                }

                @Override
                public void onDissmiss(AlertView alert) {
                    ((MainActivity) getActivity()).removeBackKeyListener();
                }

                @Override
                public void onItemClick(int position, String item) {
                    if (position == -1) {
                        return;
                    }
                    if (isHasContractHelp) {
                        if (position == 0) {
                            //合约帮助
                            WebActivity.runActivity(getActivity(), getString(R.string.string_contract_help), contractHelpUrl);

                        } else if (position == 1) {
                            //合约计算器
                            IntentUtils.goContractCalculator(getActivity());

                        } else if (position == 2 || position == 3) {
                            //多仓 或 空仓 风险限额设置
                            if (!UserInfo.isLogin()) {
                                //去登录
                                IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                            } else {
                                FuturesRiskLimitDialog futuresRiskLimitDialog = new FuturesRiskLimitDialog(getActivity(), position == 2 ? ORDER_SIDE.BUY_OPEN.getOrderSide() : ORDER_SIDE.SELL_OPEN.getOrderSide(), coinPairBean, new FuturesRiskLimitDialog.OnLoadingObserver() {
                                    @Override
                                    public void showLoading() {
                                        showProgressDialog("", "");
                                    }

                                    @Override
                                    public void hideLoading() {
                                        dismissProgressDialog();
                                    }
                                }, new FuturesRiskLimitDialog.OnDialogObserver() {
                                    @Override
                                    public void onShow(DialogInterface dialog) {

                                    }

                                    @Override
                                    public void onDismiss(DialogInterface dialog) {

                                    }

                                    @Override
                                    public void onReqHttpSuccess() {
                                        if (coinPairBean != null) {
                                            getPresenter().getOrderSetting(coinPairBean);
                                        }
                                    }

                                    @Override
                                    public void onReqHttpFaile() {

                                    }
                                });
                                futuresRiskLimitDialog.ShowDialog();
                            }
                        }

                    } else {
                        if (position == 0) {
                            //合约计算器
                            IntentUtils.goContractCalculator(getActivity());

                        } else if (position == 1 || position == 2) {
                            //多仓 或 空仓 风险限额设置
                            if (!UserInfo.isLogin()) {
                                //去登录
                                IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                            } else {
                                FuturesRiskLimitDialog futuresRiskLimitDialog = new FuturesRiskLimitDialog(getActivity(), position == 1 ? ORDER_SIDE.BUY_OPEN.getOrderSide() : ORDER_SIDE.SELL_OPEN.getOrderSide(), coinPairBean, new FuturesRiskLimitDialog.OnLoadingObserver() {
                                    @Override
                                    public void showLoading() {
                                        showProgressDialog("", "");
                                    }

                                    @Override
                                    public void hideLoading() {
                                        dismissProgressDialog();
                                    }
                                }, new FuturesRiskLimitDialog.OnDialogObserver() {
                                    @Override
                                    public void onShow(DialogInterface dialog) {

                                    }

                                    @Override
                                    public void onDismiss(DialogInterface dialog) {

                                    }

                                    @Override
                                    public void onReqHttpSuccess() {
                                        if (coinPairBean != null) {
                                            getPresenter().getOrderSetting(coinPairBean);
                                        }
                                    }

                                    @Override
                                    public void onReqHttpFaile() {

                                    }
                                });
                                futuresRiskLimitDialog.ShowDialog();
                            }
                        }
                    }

                }
            });
        }

    }

    /**
     * 获取当前可设置杠杆列表
     *
     * @return
     */
    private ArrayList<String> getCurrentCanSetLevers() {

        ArrayList<String> levers = new ArrayList<String>();    //新的可开杠杆列表
        if (coinPairBean != null) {
            if (baseTokenFutures != null) {
                String maxLimitLever = getPresenter().getMaxLimitLever(coinPairBean.getSymbolId(), currentSide);
                List<String> leversOfAll = baseTokenFutures.getLevers();    //原始全部杠杆列表
                for (int i = 0; i < leversOfAll.size(); i++) {
                    String lever = leversOfAll.get(i);
                    if (NumberUtils.sub(lever, maxLimitLever) < 0) {
                        levers.add(lever + "X");
                    }
                }
                if (!TextUtils.isEmpty(maxLimitLever)) {
                    levers.add(maxLimitLever + "X");
                }
            }
        }

        return levers;
    }

    /**
     * 更新杠杆需要放在更新下单方向之后
     */
    @Override
    public void updateLevers() {
        if (isOpenStatus && coinPairBean != null) {
            ArrayList<String> currentCanSetLevers = getCurrentCanSetLevers();
            String key = coinPairBean.getSymbolId() + isBuyMode;
            String oldSetLever = SPEx.get(key, "");
            String leverNum;
            if (!TextUtils.isEmpty(oldSetLever)) {
                leverNum = oldSetLever;
            } else {
                leverNum = getLeverNum();
            }
            leverNum = leverNum + (leverNum.endsWith("X") ? "" : "X");
            if (!currentCanSetLevers.contains(leverNum)) {
                setDefaultLeverNum();
            } else {
                setLeverNumText(leverNum);
            }
        }


    }

    /**
     * 显示杠杆列表
     */
    protected void showLeverList() {
        closeKeyBoard(editAmount);
        final ArrayList<String> currentCanSetLevers = getCurrentCanSetLevers();
        if (currentCanSetLevers != null && currentCanSetLevers.size() > 0) {
            AlertView.showSheet(getActivity(), currentCanSetLevers, null, null, getString(R.string.string_cancel), new AlertView.DialogListener() {
                @Override
                public void onShow(final AlertView alert) {
                    ((MainActivity) getActivity()).registerBackKeyListener(new MainActivity.KeyBackListener() {
                        @Override
                        public void onKeyBack() {
                            alert.dismiss();
                        }
                    });
                }

                @Override
                public void onDissmiss(AlertView alert) {
                    ((MainActivity) getActivity()).removeBackKeyListener();
                }

                @Override
                public void onItemClick(int position, String item) {
                    if (position == -1) {
                        return;
                    }
//                    lerverNumTv.setText(currentCanSetLevers.get(position));
                    setLeverNumText(currentCanSetLevers.get(position));
                    updateTradeAmountOfMoney();
                    updateMaxCanOpenCloseQuantity();
                    updateStepViewRange();
                }
            });
        } else {
            DebugLog.e("current can set levers is null");
        }

    }

    /**
     * 切换买卖tab 开平仓tab 清理数据
     */
    private void clearData() {
        triggerPrice.setText("");
        editPrice.setText("");
        editAmount.setText("");
//        priceModeControl(0,getResources().getString(R.string.string_limited_price));
        payMargin.setText(getString(R.string.string_placeholder));
        payMarginAbout.setText(getString(R.string.string_placeholder));
    }

    /**
     * 开仓/平仓-切换
     *
     * @param isOpen
     */
    private void switchOpenClose(boolean isOpen) {
        isOpenStatus = isOpen;
        clearData();
        if (isOpen) {
            balanceAvailableRela.setVisibility(View.VISIBLE);
            canCloseQuantityLL.setVisibility(View.GONE);
            payMarginLL.setVisibility(View.VISIBLE);
            leverRela.setVisibility(View.VISIBLE);

            updateAsset(quoteToken, quoteTokenName);
            setCanOpenQuantity();
        } else {
            balanceAvailableRela.setVisibility(View.GONE);
            canCloseQuantityLL.setVisibility(View.VISIBLE);
            payMarginLL.setVisibility(View.GONE);
            leverRela.setVisibility(View.GONE);

            setCanCloseQuantity();
        }

        updateCreateButtonStatus();
        //更新杠杆需要放置更新下单方向之后
        updateLevers();

    }

    /**
     * 更新最大开仓/平仓手术
     */
    private void updateMaxCanOpenCloseQuantity() {
        if (isOpenStatus) {
            setCanOpenQuantity();
        } else {
            setCanCloseQuantity();
        }
    }

    /**
     * 设置最大开仓数量
     */
    private void setCanOpenQuantity() {
        if (UserInfo.isLogin()) {
            String maxOpenQuantity = calMaxOpenQuantity();
            editAmount.setHint(getString(R.string.string_can_open) + maxOpenQuantity);
        } else {
            editAmount.setHint(getString(R.string.string_amount));
        }
    }

    /**
     * 设置可平
     */
    private void setCanCloseQuantity() {
        if (!isOpenStatus) {//平仓状态下
            if (UserInfo.isLogin()) {

                if (mCurrentTradableInfo != null) {
                    String canCloseNum;
                    //有可交易信息信息
                    if (isBuyMode) {
                        canCloseNum = mCurrentTradableInfo.getShortAvailable();
                    } else {
                        canCloseNum = mCurrentTradableInfo.getLongAvailable();
                    }
                    canCloseNum = NumberUtils.roundFormatDown(canCloseNum, digitBase);
                    closeNumTv.setText(canCloseNum);
                    editAmount.setHint(getString(R.string.string_can_close) + canCloseNum);
                } else {
                    closeNumTv.setText(getString(R.string.string_placeholder));
                }
            } else {
                editAmount.setHint(getString(R.string.string_amount));
                closeNumTv.setText(getString(R.string.string_placeholder));
            }
        }
    }

    /**
     * 更新下单按钮文案
     */
    private void updateCreateButtonStatus() {
        if (!UserInfo.isLogin()) {
            btnCreateOrder.setText(getString(R.string.string_login));
        } else {
            if (isOpenStatus) {
                //开仓
                if (isBuyMode) {
                    btnCreateOrder.setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_futures_open_long) + ")");
                } else {
                    btnCreateOrder.setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_futures_open_short) + ")");
                }

            } else {
                //平仓
                if (isBuyMode) {
                    btnCreateOrder.setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_futures_close_short) + ")");
                } else {
                    btnCreateOrder.setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_futures_close_long) + ")");
                }
            }
        }

        if (isOpenStatus) {
            buyTabTx.setText(getString(R.string.string_futures_open_long));
            sellTabTx.setText(getString(R.string.string_futures_open_short));
            //开仓
            if (isBuyMode) {
                currentSide = ORDER_SIDE.BUY_OPEN.getOrderSide();
            } else {
                currentSide = ORDER_SIDE.SELL_OPEN.getOrderSide();
            }

        } else {
            buyTabTx.setText(getString(R.string.string_futures_close_short));
            sellTabTx.setText(getString(R.string.string_futures_close_long));
            //平仓
            if (isBuyMode) {
                currentSide = ORDER_SIDE.BUY_CLOSE.getOrderSide();
            } else {
                currentSide = ORDER_SIDE.SELL_CLOSE.getOrderSide();
            }
        }
    }

    /**
     * 显示价格模式选择 限价/市价
     */
    private void showPriceModeSelect() {
        closeKeyBoard(editAmount);

        if (currentEntrustOrderType == ORDER_ENTRUST_TYPE.STOP.getEntrustType()) {
            //TODO 计划委托暂不支持价格模式选择 目前只支持限价
            return;
        }

        ArrayList<String> priceModeList = new ArrayList<>();
        priceModeList.add(getResources().getString(R.string.string_limited_price));
        priceModeList.add(getResources().getString(R.string.string_market_price));
        priceModeList.add(getResources().getString(R.string.string_rival_price));
        priceModeList.add(getResources().getString(R.string.string_queuing_price));
        priceModeList.add(getResources().getString(R.string.string_over_price));
        AlertView.showSheet(getActivity(), priceModeList, null, null, getString(R.string.string_cancel), new AlertView.DialogListener() {
            @Override
            public void onShow(final AlertView alert) {
                ((MainActivity) getActivity()).registerBackKeyListener(new MainActivity.KeyBackListener() {
                    @Override
                    public void onKeyBack() {
                        alert.dismiss();
                    }
                });
            }

            @Override
            public void onDissmiss(AlertView alert) {
                ((MainActivity) getActivity()).removeBackKeyListener();
            }

            @Override
            public void onItemClick(int position, String item) {
                if (position == -1) {
                    return;
                }

                priceModeControl(position, item);

            }
        });
    }

    private void priceModeControl(int position, String priceMode) {
        editPriceUnit.setText(priceMode);
        priceMarketTx.setText(priceMode);
        if (position == 0) {
            //限价
            switchPriceMode(true);
        } else {
            //非限价
            switchPriceMode(false);
        }
        if (position == 0) {
            //切换到:限价
            currentPriceType = PRICE_TYPE.INPUT.getPriceType();
            priceMarketTx.setVisibility(View.GONE);
            editPriceRela.setVisibility(View.VISIBLE);
        } else if (position == 1) {
            //切换到:市价
            currentPriceType = PRICE_TYPE.MARKET_PRICE.getPriceType();
            priceMarketTx.setVisibility(View.VISIBLE);
            editPriceRela.setVisibility(View.GONE);
        } else if (position == 2) {
            //对手价
            currentPriceType = PRICE_TYPE.OPPONENT.getPriceType();

        } else if (position == 3) {
            //排队价
            currentPriceType = PRICE_TYPE.QUEUE.getPriceType();
        } else if (position == 4) {
            //超价
            currentPriceType = PRICE_TYPE.OVER.getPriceType();
        }
    }

    /**
     * 下单
     *
     * @param isBuyMode
     */
    protected void createOrder(final boolean isBuyMode) {
        /**交易下单规则粗略校验**************/

        if (!checkOpenFutureStatus()) { //检查是否开通合约协议
            return;
        }

        String triggerPriceStr = triggerPrice.getText().toString().trim();
        if (currentEntrustOrderType.equals(ORDER_ENTRUST_TYPE.STOP.getEntrustType())) {
            //计划委托
            if (TextUtils.isEmpty(triggerPriceStr)) {
                ToastUtils.showShort(getActivity(), getString(R.string.string_input_trigger_price));
                return;
            }
        } else {
            triggerPriceStr = "";
        }

        String price = editPrice.getText().toString().trim();
        if (isLimitedPrice) {
            if (TextUtils.isEmpty(price)) {
                ToastUtils.showShort(getActivity(), getString(R.string.string_prompt_input_price));
                return;
            }
            if (Double.valueOf(price) <= 0) {
                ToastUtils.showShort(getActivity(), getString(R.string.string_prompt_input_price));
                return;
            }
        }

        final String amount = editAmount.getText().toString().trim();
        if (TextUtils.isEmpty(amount)) {
//            if (isBuyMode && !isLimitedPrice) {
//                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_amount_of_money));
//            } else {
            ToastUtils.showShort(getActivity(), getString(R.string.string_prompt_input_amount));
//            }
            return;
        }
        if (Double.valueOf(amount) <= 0) {
            /*if (isBuyMode && !isLimitedPrice) {
                ToastUtils.showShort(getActivity(),getString(R.string.string_prompt_input_amount_of_money));
            } else {*/
            ToastUtils.showShort(getActivity(), getString(R.string.string_prompt_input_amount));
            //}
            return;
        }
        if (coinPairBean != null) {
            //最小交易数量
            String minTradeQuantity = coinPairBean.getMinTradeQuantity();
            //最小交易额
            String minTradeAmount = coinPairBean.getMinTradeAmount();
            if (isLimitedPrice) {//限价
                String minPricePrecision = coinPairBean.getMinPricePrecision();
                //最小交易价格
                if (!TextUtils.isEmpty(minPricePrecision)) {
                    if (NumberUtils.sub(price, minPricePrecision) < 0) {
                        ToastUtils.showShort(getActivity(), getString(R.string.string_min_trade_price, minPricePrecision) + quoteTokenName);
                        return;
                    }
                }

                //最小交易数量
                if (!TextUtils.isEmpty(minTradeQuantity)) {
                    if (NumberUtils.sub(amount, minTradeQuantity) < 0) {
                        ToastUtils.showShort(getActivity(), getString(R.string.string_min_trade_quantity, minTradeQuantity) + quantityUnit);
                        return;
                    }
                }

                //最小交易额
//                if (!TextUtils.isEmpty(minTradeAmount)) {
//                    //TODO 算法待处理
//                    if (NumberUtils.sub(String.valueOf(NumberUtils.mul(price, amount)), minTradeAmount) < 0) {
//                        ToastUtils.showShort(getActivity(), getString(R.string.string_min_trade_amount, minTradeAmount) + quoteTokenName);
//                        return;
//                    }
//                }
            } else {//非限价
               /* if (isBuyMode) {
                    //最小交易额
                    if (!TextUtils.isEmpty(minTradeAmount)) {
                        //amount 为输入金额
                        if (NumberUtils.sub(amount, minTradeAmount) < 0) {
                            ToastUtils.showShort(getActivity(),getString(R.string.string_min_trade_amount, minTradeAmount)+quoteTokenName);
                            return;
                        }
                    }
                } else */
                {
                    //最小交易数量
                    if (!TextUtils.isEmpty(minTradeQuantity)) {
                        if (NumberUtils.sub(amount, minTradeQuantity) < 0) {
                            ToastUtils.showShort(getActivity(), getString(R.string.string_min_trade_quantity, minTradeQuantity) + quantityUnit);
                            return;
                        }
                    }
                }

            }
        } else {
            ToastUtils.showShort(getActivity(), getString(R.string.string_retry_select_trade_symbol));
            return;
        }

        /** 最大交易额/量判断 **********/
        if (isBuyMode) {//买入
            if (isLimitedPrice) {//限价
                //最大交易额
//                if (!TextUtils.isEmpty(getQuoteTokenAsset())) {
//                    if (NumberUtils.sub(String.valueOf(NumberUtils.mul(price, amount)), getQuoteTokenAsset()) > 0) {
//                        ToastUtils.showShort(getActivity(), getString(R.string.string_balance_not_enough));
//                        return;
//                    }
//                } else {
//                    ToastUtils.showShort(getActivity(), getString(R.string.string_balance_not_enough_swipy_refresh));
//                    return;
//                }
            } else {//市价
                //最大交易额
                /*if (!TextUtils.isEmpty(getQuoteTokenAsset())) {
                    //amount 为输入金额
                    if (NumberUtils.sub(String.valueOf(NumberUtils.mul(NumberUtils.mul(currentTicker.getC() , amount) , 1.1d)), getQuoteTokenAsset()) > 0) {
                        ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough));
                        return;
                    }
                } else {
                    ToastUtils.showShort(getActivity(),getString(R.string.string_balance_not_enough_swipy_refresh));
                    return;
                }*/
            }

        } else {//卖出

            //最大交易数量
//            if (!TextUtils.isEmpty(getCanCloseNum())) {
//                if (NumberUtils.sub(amount, getCanCloseNum()) > 0) {
//                    ToastUtils.showShort(getActivity(), getString(R.string.string_balance_not_enough));
//                    return;
//                }
//            } else {
//                ToastUtils.showShort(getActivity(), getString(R.string.string_balance_not_enough_swipy_refresh));
//                return;
//            }
        }

        String lever = getLeverNum();
        if (isOpenStatus) {
            //开仓
            if (TextUtils.isEmpty(lever)) {
                ToastUtils.showShort(getString(R.string.string_select_lever));
                return;
            }
        } else {
            //平仓没有杠杆
            lever = "";
        }

        String clientOrderId = System.currentTimeMillis() + "";
        //去下单
        getPresenter().createOrder(exchangeId, clientOrderId, symbol, currentSide, currentEntrustOrderType, price, currentPriceType, triggerPriceStr, amount, lever);


//        String baseAsset = baseTokenAsset;
//        if (TextUtils.isEmpty(baseAsset))
//            baseAsset = "0";
//        double leftAsset = NumberUtils.sub(amount, baseAsset);
//
//
//        if (OptionCreateOrderTipDialog.getOptionTipSPShow() == true && isBuyMode == false && leftAsset > 0d && coinPairBean.baseTokenOption != null) {
//            String assetVaule = String.valueOf(NumberUtils.mul(String.valueOf(leftAsset), coinPairBean.baseTokenOption.maxPayOff));
//            assetVaule = NumberUtils.roundFormatDown(assetVaule, digitPrice);
//            String tipText = String.format(getString(R.string.string_option_create_tip_value), assetVaule, quoteTokenName);
//
//            final OptionCreateOrderTipDialog optionCreateOrderTipDialog = new OptionCreateOrderTipDialog(getActivity());
//            optionCreateOrderTipDialog.setShowText(tipText);
//            optionCreateOrderTipDialog.setNegativeButton(getString(R.string.string_sure), new View.OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    if (optionCreateOrderTipDialog.getTipChecked() == true) {
//                        OptionCreateOrderTipDialog.setOptionTipSP(true);
//                    }
//
//                    getPresenter().createOrder(exchangeId,clientOrderId, symbol,currentSide,currentEntrustOrderType,price,currentPriceType, triggerPriceStr,amount,Integer.valueOf(lever));
//                    if (optionCreateOrderTipDialog.isShowing()) {
//                        optionCreateOrderTipDialog.dismiss();
//                    }
//                }
//            });
//            optionCreateOrderTipDialog.setPositiveButton(getActivity().getString(R.string.string_cancel), new View.OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    // 取消的操作
//                    if (optionCreateOrderTipDialog.isShowing()) {
//                        optionCreateOrderTipDialog.dismiss();
//                    }
//                }
//            });
//            optionCreateOrderTipDialog.show();
//        } else {
//            //去下单
//            getPresenter().createOrder(exchangeId,clientOrderId, symbol,currentSide,currentEntrustOrderType,price,currentPriceType, triggerPriceStr,amount,Integer.valueOf(lever));
//        }

    }

    @Override
    public void createOrderSuccess() {
        editPrice.setText("");
        editAmount.setText("");
    }

    @Override
    public CoinPairBean getCurrentCoinInfoBean() {
        return coinPairBean;
    }

    @Override
    public int getDigitBase() {
        return digitBase;
    }

    @Override
    public String getExchangeId() {
        return exchangeId;
    }

    @Override
    public String getSymbols() {
        return symbol;
    }

    @Override
    public void showLatestPrice(TickerBean data) {
        updateLatestPrice(data);
    }


    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        getPresenter().refresh();
        refreshLayout.finishRefresh(1000);
        getPresenter().getOrderSetting(coinPairBean);
    }

    public class CustomSnapHelper extends LinearSnapHelper {
        private OrientationHelper mHorizontalHelper;

        @Override
        public int[] calculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView) {
            int[] out = new int[2];
            //判断支持水平滚动，修改水平方向的位置，是修改的out[0]的值
            if (layoutManager.canScrollVertically()) {
                out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager));
            } else {
                out[0] = 0;
            }
            return out;
        }

        private int distanceToStart(View targetView, OrientationHelper helper) {
            return helper.getDecoratedStart(targetView) - helper.getStartAfterPadding();
        }

        @Override
        public View findSnapView(RecyclerView.LayoutManager layoutManager) {
            return findStartView(layoutManager, getHorizontalHelper(layoutManager));
        }

        private View findStartView(RecyclerView.LayoutManager layoutManager,
                                   OrientationHelper helper) {
            if (layoutManager instanceof LinearLayoutManager) {
                int firstChild = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                int lastChild = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                if (firstChild == RecyclerView.NO_POSITION) {
                    return null;
                }
                //这行的作用是如果是最后一个，翻到最后一条，解决显示不全的问题
                if (lastChild == layoutManager.getItemCount() - 1) {
                    return layoutManager.findViewByPosition(lastChild);
                }
                View child = layoutManager.findViewByPosition(firstChild);
                //获取偏左显示的Item
                if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2
                        && helper.getDecoratedEnd(child) > 0) {
                    return child;
                } else {
                    return layoutManager.findViewByPosition(firstChild + 1);
                }
            }
            return super.findSnapView(layoutManager);
        }

        private OrientationHelper getHorizontalHelper(
                RecyclerView.LayoutManager layoutManager) {
            if (mHorizontalHelper == null) {
                mHorizontalHelper = OrientationHelper.createVerticalHelper(layoutManager);
            }
            return mHorizontalHelper;
        }
    }


    public void getTicker() {
        if (getPresenter() != null)
            getPresenter().getTicker();
    }

    public void requestDepthData() {
        if (getPresenter() != null)
            getPresenter().requestDepthData();
    }


    @Override
    public void showOpenOrders(List<FuturesOrderResponse> datas) {
        if (currentShowOrdersTab != ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType()) {
            return;
        }
        recyclerView.setAdapter(openOrdersAdapter);
        if (!UserInfo.isLogin()) {
            if (!currentOrderDatas.isEmpty()) {
                currentOrderDatas.clear();
                openOrdersAdapter.notifyDataSetChanged();
            }
            return;
        }
        if (datas != null) {
            currentOrderDatas.clear();
            currentOrderDatas.addAll(datas);
            openOrdersAdapter.notifyDataSetChanged();
        }

        loadEntrustOrdersPriceIntoCache(datas);

    }

    private String bidPrice = "";
    private String askPrice = "";

    private void loadEntrustOrdersPriceIntoCache(List<FuturesOrderResponse> datas) {
        bidPrice = "";
        askPrice = "";
        if (datas != null) {
            for (FuturesOrderResponse data : datas) {
                String price = data.getPrice();
                price = NumberUtils.stripTrailingZeros(price);
                if (KlineUtils.isFuturesBuyOrder(getActivity(), data.getSide())) {
                    bidPrice = bidPrice + price + ";";
                } else {
                    askPrice = askPrice + price + ";";
                }
            }
        }
    }

    public boolean isCurrentBidOrderPrice(String price) {
        price = NumberUtils.stripTrailingZeros(price);
        return bidPrice.contains(price + ";");
    }

    @Override
    public List<BookListBean> getBookListData() {
        return bookListData;
    }

    public boolean isCurrentAskOrderPrice(String price) {
        price = NumberUtils.stripTrailingZeros(price);
        return askPrice.contains(price + ";");
    }

    @Override
    public void showPlanningOrders(List<FuturesOrderResponse> datas) {
        if (currentShowOrdersTab != ORDER_TYPE.ORDER_TYPE_PLANNING_ENTRUSTMENT.getOrderType()) {
            return;
        }
        recyclerView.setAdapter(planningEntrustAdapter);
        if (!UserInfo.isLogin()) {
            if (!mPlanningOrders.isEmpty()) {
                mPlanningOrders.clear();
                planningEntrustAdapter.notifyDataSetChanged();
            }
            return;
        }
        if (datas != null) {
            mPlanningOrders.clear();
            mPlanningOrders.addAll(datas);
            planningEntrustAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void showHoldOrders(List<FuturesPositionOrder> datas) {
        if (currentShowOrdersTab != ORDER_TYPE.ORDER_TYPE_HOLD.getOrderType()) {
            return;
        }
        recyclerView.setAdapter(mPositionAdapter);
        if (!UserInfo.isLogin()) {
            if (!holdOrders.isEmpty()) {
                holdOrders.clear();
                mPositionAdapter.notifyDataSetChanged();
            }
            return;
        }
        if (datas != null) {
            holdOrders.clear();
            holdOrders.addAll(datas);
            mPositionAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showFundingRates(FuturesFundingRatesResponse response) {
        if (response != null) {
            List<FuturesFundingRate> fundingRatesList = response.getArray();
            for (FuturesFundingRate futuresFundingRate : fundingRatesList) {
                if (futuresFundingRate != null) {
                    fundingRateMap.put(futuresFundingRate.getTokenId(), futuresFundingRate);
                }
            }
        }
    }

    @Override
    public void showTradableInfo(TradableBean tradableBean) {
        mCurrentTradableInfo = tradableBean;
        if (mCurrentTradableInfo != null) {
            TradableBean.ProfitLossBean profitLoss = mCurrentTradableInfo.getProfitLoss();
            if (profitLoss != null) {
                String coinAvailable = profitLoss.getCoinAvailable();
                if (!TextUtils.isEmpty(coinAvailable)) {
                    //更新一下当前资产，防止futures_balance未推送
                    quoteTokenAsset = coinAvailable;
                }
            }
        }
        updateAsset(quoteToken, quoteTokenName);

    }

}
